import { useEffect, useState } from 'react'
import { Card, Button, Table, Switch, message, Popconfirm, Drawer, Form, Input, Tree } from 'antd'
import { getRoleList, changStatus, delRole, addRole, editRole, setRole } from '@/api/role'
import type { TableProps } from 'antd'
import type { TreeProps } from 'antd'
import { getRuleList } from '@/api/rule'
function role() {
  const [roleList, setRoleList] = useState([])
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  useEffect(() => {
    getList()
  }, [page])
  const getList = () => {
    getRoleList(page).then(res => {
      if (res.status === 200) {
        setRoleList(res.data.list)
        setTotal(res.data.totalCount)
      }
    })
  }
  const switchChange = (data: any) => {
    changStatus(data.id, { status: !data.status }).then(res => {
      if (res.status === 200) {
        message.success('修改成功')
        getList()
      }
    })
  }
  const delRoleBtn = (id: number) => {
    delRole(id).then(res => {
      if (res.status === 200) {
        message.success('删除成功')
        getList()
      }
    })
  }
  const columns: TableProps<any>['columns'] = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '角色描述',
      dataIndex: 'desc',
      key: 'desc'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (_, record) => (
        <div>
          <Switch
            checked={record.status}
            onChange={() => {
              switchChange(record)
            }}
          />
        </div>
      )
    },

    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <div>
          <p
            style={{ color: '#1677ff', cursor: 'pointer', display: 'inline-block' }}
            onClick={() => {
              setAuthBtn(record)
            }}
          >
            配置权限
          </p>
          <p
            style={{ color: '#1677ff', cursor: 'pointer', display: 'inline-block', margin: '0 10px' }}
            onClick={() => {
              editBtn(record)
            }}
          >
            修改
          </p>
          <Popconfirm
            placement='bottom'
            title=''
            description='是否要删除该角色？'
            okText='确认'
            cancelText='取消'
            onConfirm={() => {
              delRoleBtn(record.id)
            }}
          >
            <p
              style={{ color: '#ff7885', cursor: 'pointer', display: 'inline-block' }}
              onClick={() => {
                editBtn(record)
              }}
            >
              删除
            </p>
          </Popconfirm>
        </div>
      )
    }
  ]
  // 添加/修改角色
  const [openDrawer, setOpenDrawer] = useState(false)
  const [form] = Form.useForm()
  const [editId, setEditId] = useState(0)
  const addRoleBtn = () => {
    form.resetFields()
    setOpenDrawer(true)
  }
  const addSave = () => {
    form.validateFields().then(values => {
      if (editId !== 0) {
        editRole(editId, values)
          .then(res => {
            if (res.status === 200) {
              message.success('修改成功')
              getList()
              setOpenDrawer(false)
            }
          })
          .catch(err => {
            message.error(err)
          })
        return
      }
      addRole(values)
        .then(res => {
          if (res.status === 200) {
            message.success('添加成功')
            getList()
            setOpenDrawer(false)
          }
        })
        .catch(err => {
          message.error(err)
        })
    })
  }
  const editBtn = (data: any) => {
    setEditId(data.id)
    form.setFieldsValue({
      name: data.name,
      desc: data.desc,
      status: data.status
    })
    setOpenDrawer(true)
  }
  // 配置权限
  const [authDrawer, setAuthDrawer] = useState(false)
  const [ruleList, setRuleList] = useState([])
  const setAuthBtn = (data: any) => {
    setEditId(data.id)
    getRuleList().then(res => {
      setRuleList(res.data.list)
      setCheckedKeys(data.rules.map((o: any) => o.id))
      setExpandedKeys(res.data.list.map((o: any) => o.id))
    })
    setAuthDrawer(true)
  }
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([])
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([])
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([])
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true)

  const setRoleBtn = () => {
    setRole({ id: editId, rule_ids: checkedKeys }).then(res => {
      if (res.status === 200) {
        message.success('设置成功')
        setAuthDrawer(false)
        getList()
      }
    })
  }

  const onExpand: TreeProps['onExpand'] = expandedKeysValue => {
    setExpandedKeys(expandedKeysValue)
    setAutoExpandParent(false)
  }

  const onCheck: TreeProps['onCheck'] = checkedKeysValue => {
    setCheckedKeys(checkedKeysValue as React.Key[])
  }

  const onSelect: TreeProps['onSelect'] = selectedKeysValue => {
    setSelectedKeys(selectedKeysValue)
  }

  const btn = (
    <div style={{ textAlign: 'right' }}>
      <Button type='primary' size='large' onClick={addSave}>
        确认
      </Button>
      <Button
        size='large'
        style={{ marginLeft: '15px' }}
        onClick={() => {
          setOpenDrawer(false)
        }}
      >
        取消
      </Button>
    </div>
  )
  const btn2 = (
    <div style={{ textAlign: 'right' }}>
      <Button type='primary' size='large' onClick={setRoleBtn}>
        提交
      </Button>
      <Button
        size='large'
        style={{ marginLeft: '15px' }}
        onClick={() => {
          setAuthDrawer(false)
        }}
      >
        取消
      </Button>
    </div>
  )
  return (
    <>
      <Card>
        <Button onClick={addRoleBtn}>新增角色</Button>
        <Table
          columns={columns}
          dataSource={roleList}
          pagination={{ total }}
          rowKey='id'
          onChange={(e: any) => {
            setPage(e.current)
          }}
        />
      </Card>
      <Drawer
        title='新增角色'
        onClose={() => {
          setOpenDrawer(false)
        }}
        open={openDrawer}
        footer={btn}
      >
        <Form form={form} autoComplete='off' style={{ maxWidth: 600 }} layout='vertical'>
          <Form.Item label='角色名称' name='name' rules={[{ required: true, message: '请输入角色名称' }]}>
            <Input />
          </Form.Item>
          <Form.Item label='角色描述' name='desc' rules={[{ required: true, message: '请输入角色描述' }]}>
            <Input />
          </Form.Item>
          <Form.Item label='状态' name='status' initialValue={true}>
            <Switch defaultChecked />
          </Form.Item>
        </Form>
      </Drawer>
      <Drawer
        title='配置权限'
        onClose={() => {
          setAuthDrawer(false)
        }}
        open={authDrawer}
        footer={btn2}
      >
        <Tree
          checkable
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          onCheck={onCheck}
          checkedKeys={checkedKeys}
          onSelect={onSelect}
          selectedKeys={selectedKeys}
          treeData={ruleList}
          fieldNames={{ title: 'name', key: 'id', children: 'child' }}
        />
      </Drawer>
    </>
  )
}
export default role
